#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include "TCPUtils.h"

int initClient(const char *host, uint16_t port) {
	int tcp_socket;
	struct sockaddr_in dest;
	int ret;
	// 申请TCP的socket
	tcp_socket = socket(AF_INET, SOCK_STREAM, 0);
	if (tcp_socket < 0) {
		perror("socket");
		return -1;
	}
	// 初始化目标IP和port，若host为域名，则发起DNS请求
	memset(&dest, 0, sizeof(dest));
	dest.sin_family = AF_INET;
	dest.sin_port = htons(port);
	struct hostent *pHostent = gethostbyname(host);
	if (pHostent == NULL) {
		fprintf(stderr, "get host name %d: %s\n", h_errno, hstrerror(h_errno));
		return -1;
	}
	dest.sin_addr = *(struct in_addr *)pHostent->h_addr;
    // 发起三次握手
	ret = connect(tcp_socket, (const struct sockaddr *) &dest, sizeof(dest));
	if (ret < 0) {
		perror("connect");
		return -1;
	}
	printf("connect success!\n");
	return tcp_socket;
}

int initTCPServer(unsigned short port) {
	int tcp_socket;
	struct sockaddr_in self;
	int ret;
	// 申请TCP的socket
	tcp_socket = socket(AF_INET, SOCK_STREAM, 0);
	if (tcp_socket < 0) {
		perror("socket");
		return -1;
	}
    // 配置地址复用，解决2MLS问题
	int val = 1;
	ret = setsockopt(tcp_socket, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
	if (ret < 0) {
		perror("set sock opt");
		return -1;
	}
	// 绑定端口
	memset(&self, 0, sizeof(self));
	self.sin_family = AF_INET;
	self.sin_port = htons(port);
	self.sin_addr.s_addr = htonl(INADDR_ANY);
	ret = bind(tcp_socket, (const struct sockaddr *) &self, sizeof(self));
	if (ret < 0) {
		perror("bind");
		return -1;
	}

	listen(tcp_socket, 5);
	return tcp_socket;
}